/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package todonet;

import java.util.ArrayList;
import java.util.List;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author DNS
 */
public class ToDoListTreeModel implements TreeModel {

    private ToDoTask _root;
    private List<TreeModelListener> listeners = new ArrayList<TreeModelListener>();
    private ITaskFilter filter = null;

    public void setFilter(ITaskFilter filter)
    {
        this.filter = filter;
    }

    public ITaskFilter getFilter()
    {
        return filter;
    }

    public ToDoListTreeModel(ToDoTask rootTask)
    {
        _root = rootTask;
    }

    public Object getRoot() {
        return _root;
    }

    private List<ToDoTask> getFilteredChildList(ToDoTask task)
    {
        if (getFilter() == null)
            return task.getChilds();
        List<ToDoTask> filteredList = new ArrayList<ToDoTask>();
        for (ToDoTask t : task.getChilds())
            if (getFilter().accept(t))
                filteredList.add(t);
        return filteredList;
    }

    public Object getChild(Object parent, int index) {
        return getFilteredChildList((ToDoTask) parent).get(index);
    }

    public int getChildCount(Object parent) {
        return getFilteredChildList((ToDoTask) parent).size();
    }

    public boolean isLeaf(Object node) {
        return getFilteredChildList((ToDoTask) node).isEmpty();
    }

    public void valueForPathChanged(TreePath path, Object newValue) {
       ///???????
    }

    public int getIndexOfChild(Object parent, Object child) {
        return getFilteredChildList((ToDoTask) parent).indexOf(child);
    }

    public void addTreeModelListener(TreeModelListener l) {
        listeners.add(l);
    }

    public void removeTreeModelListener(TreeModelListener l) {
        listeners.remove(l);
    }

}
